/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.zz.production.chargeback.controller;

import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.util.CustomerNumberEncryptionUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.iboss.base.util.datatable.DataTableUtils;
import net.dgg.iboss.base.util.datatable.domain.DataTableRequest;
import net.dgg.iboss.base.util.datatable.domain.DataTableResponse;
import net.dgg.tmd.foundation.platform.annotation.AuthOpt;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.utils.OrderHandleUtils;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.production.chargeback.service.ZzAuditOrderServic;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.inProcess.entity.ProductNodeFlow;
import net.dgg.zz.production.inProcess.service.ZzInProcessService;
import net.fblock.log.NLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @class_name: AuditOrderController
 * @package: net.dgg.dggcloud.web.action.iboss.sc
 * @describe: TODO  待审核的生产订单-控制层
 * @creat_user: 孙上峰
 * @creat_date: 2018/5/8
 * @creat_time: 11:38
 **/
@Controller
@RequestMapping(value = "/zzsc/audit")
public class ZzAuditOrderController extends DggBaseController {
    @Autowired
    private ZzAuditOrderServic zzAuditOrderServic;
    @Autowired
    private ZzInProcessService zzInProcessService;
    @Autowired
    protected DesUtil desUtil;
    @Autowired
    protected CommonMangerExtService zzCommonMangerExtService;
    @Autowired
    protected SessionManager sessionManager;
    @Autowired
    private TranslateUtil translateUtil;

    /**
     * 初始化界面
     */
    @RequestMapping(value = "/index")
    public String index(Model model, String status) {
        List list = new ArrayList<>();
        list = zzCommonMangerExtService.queryTreeBookListByCode(ScProductConstant.RETURENED_REASON, 1, null);
        model.addAttribute("list", list); //退单原因
        return "zzsc/auditOrder/audit_order_list";
    }

    /**
     * 待审核分页列表
     * 孙上峰
     *
     * @param params {codeName:模块名称}
     * @return
     */
    @RequestMapping(value = "/query_audit_list")
    @ResponseBody
    public DataTableResponse queryAuditList(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        UserEntity userEntity = sessionManager.getCurrentUser();
        params.put("start", r.getStart());
        params.put("limit", r.getLength());
        params.put("userEntity", userEntity.getId()); //当前登录人auditorId
        params.put("auditor", userEntity.getId()); //当前审核人
        params.put("status", ScProductConstant.SC_ORDER_CHARGEBACK_DSH);//退单待审核
        if (!net.dgg.iboss.base.util.StringUtils.isEmptyObj(params.get("customerPhone"))) {
            params.put("customerPhone", desUtil.encrypt(params.get("customerPhone").toString()));
        }

        Map fileMap = new HashMap();
        fileMap.put("abandonReasonTime", "abandonReasonTime");
        fileMap.put("receiveOrderDate", "receiveOrderDate");
        fileMap.put("lastRemarkTime", "lastRemarkTime");
        OrderHandleUtils.getOrderCol(r, params, fileMap);
        List<Map> listPage = zzAuditOrderServic.queryAuditListPage(params);
        String[] transColum = {"abandonReason"};
        listPage = translateUtil.translateList(transColum, listPage);
        String[] hideColum = {"customerPhone"};
        listPage = desUtil.decryptListMap(hideColum, listPage);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, listPage);
        Integer count = Integer.parseInt(params.get("count").toString());
        return new DataTableResponse(r.getDraw(), count, count, listPage, "");
    }

    /**
     * 退废单审核
     * 孙上峰
     *
     * @return
     */
    @RequestMapping(value = "/audit_order_page")
    public String auditOrder(Model model, Long id) {
        Map map = new HashMap<>();
        try {
            ProductOrder scProductOrder = zzInProcessService.getScProductOrderById(id);
            //---------拿到节点流程-------------
            String auditLevel = "1";
            if(StringUtils.isEmpty(scProductOrder.getFlowContent())){
                ProductNodeFlow scProductNodeFlow = zzAuditOrderServic.queryNodeFlowById(scProductOrder.getNodeFlowId());
                    auditLevel=scProductNodeFlow.getExamineGrade().toString();
            }else{
                auditLevel = zzAuditOrderServic.queryAuditLevel(scProductOrder.getFlowContent());
            }

            model.addAttribute("scProductNodeFlow", auditLevel);
            map = zzAuditOrderServic.auditOrder(id);
            model.addAttribute("map", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "zzsc/auditOrder/audit_order_page";
    }

    /**
     * 变更审核人
     * 孙上峰
     *
     * @return
     */
    @RequestMapping(value = "/update_flow_user")
    public String updateFlowUser(Model model, Long id) {
        Map map = new HashMap<>();
        try {
            //---------拿到节点流程-------------
            map = zzAuditOrderServic.auditOrder(id);
            model.addAttribute("map", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "zzsc/auditOrder/update_flow_user";
    }

    /**
     * 审核退废订单
     *
     * @param request
     * @return 孙上峰
     */
    @NLog
    @AuthOpt(code = "ZZSC_AUDIT")
    @RequestMapping("/audit_or_chargeback_order")
    @ResponseBody
    public Object auditOrChargeBackOrder(HttpServletRequest request) {
        try {
            String id = request.getParameter("id");
            String type = request.getParameter("type");
            String auditorId = request.getParameter("auditorId");
            String remark = request.getParameter("remark");
            UserEntity userEntity = sessionManager.getCurrentUser();
            this.zzAuditOrderServic.auditOrChargeBackOrder(id, type, auditorId, remark, userEntity);
            return this.getSuccessResponse("success!");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }

    /**
     * 变更审核人
     *
     * @param request
     * @return 孙上峰
     */
    @NLog
    @AuthOpt(code = "ZZSC_UPDATE_AUDIT_USER")
    @RequestMapping("/update_auditor")
    @ResponseBody
    public Object updateAuditor(HttpServletRequest request) {
        try {
            String id = request.getParameter("id");
            String auditorId = request.getParameter("auditorId");
            String remark = request.getParameter("remark");
            this.zzAuditOrderServic.updateAuditor(id, auditorId, remark);
            return this.getSuccessResponse("success!");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }

    /**
     * 撤回
     *
     * @param id
     * @return 孙上峰
     */
    @NLog
    @AuthOpt(code = "ZZSC_TO_TITHDRAW")
    @RequestMapping("/to_tithdraw_order")
    @ResponseBody
    public Object toTithdrawOrder(Long id) {
        try {
            this.zzAuditOrderServic.toTithdrawOrder(id);
            return this.getSuccessResponse("success!");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }

    /**
     * 获取当前登陆人有审核人角色的人员
     * 孙上峰
     * @return
     */
    @RequestMapping("auditor_user")
    @ResponseBody
    public Object getauditorUser() {
        Map map = new HashMap<>();
        List<Map> auditorUser = new ArrayList<>();
        //获取当前登录的人部门
        Map orgMap = zzCommonMangerExtService.findBusDeptById(sessionManager.getCurrentUser().getOrgId());
        if (orgMap != null && orgMap.size() != 0) {
            //拿到事业部及以下的部门id
            map.put("orgId", orgMap.get("id"));
            map.put("locked", 0);
            map.put("code", "ZZSC_AUDITOR");//zzsc_admin  ZZSC_AUDITOR
            //获取当前登陆人有审核人角色的人员
            auditorUser = zzCommonMangerExtService.searchUserByMap(map);
        }
        return auditorUser;
    }

    /**
    * <p>@Description 团队退单待审核</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/9/28 0028 11:38 创建时间</p>
    * <p>@return</p>
    */
    @NLog
    @RequestMapping(value = "/team_audit_order_list")
    public String indteamAuditOrderList(Model model) {
        List list = zzCommonMangerExtService.queryTreeBookListByCode(ScProductConstant.RETURENED_REASON, 1, null);
        model.addAttribute("list", list); //退单原因
        return "zzsc/team/team_audit_order_list";
    }

    /**
    * <p>@Description 团队退单待审核数据</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/9/28 0028 11:39 创建时间</p>
    * <p>@return</p>
    */
    @NLog
    @RequestMapping(value = "/team_audit_order_list_data")
    @ResponseBody
    public DataTableResponse teamAuditOrderListData(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("start", r.getStart());
        params.put("limit", r.getLength());
        params.put("status", ScProductConstant.SC_ORDER_CHARGEBACK_DSH);//退单待审核
        if (!net.dgg.iboss.base.util.StringUtils.isEmptyObj(params.get("customerPhone"))) {
            params.put("customerPhone", desUtil.encrypt(params.get("customerPhone").toString()));
        }
        Map fileMap = new HashMap();
        fileMap.put("signTime", "signTime");
        fileMap.put("lastRemarkTime", "lastRemarkTime");
        OrderHandleUtils.getOrderCol(r, params, fileMap);
        List<Map> listPage = zzAuditOrderServic.teamAuditOrderListData(params);
        String[] transColum = {"abandonReason"};
        listPage = translateUtil.translateList(transColum, listPage);
        String[] hideColum = {"customerPhone"};
        listPage = desUtil.decryptListMap(hideColum, listPage);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, listPage);
        Integer count = Integer.parseInt(params.get("count").toString());
        return new DataTableResponse(r.getDraw(), count, count, listPage, "");
    }



    /**
     * <p>@Description 团队退单驳回</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/28 0028 11:38 创建时间</p>
     * <p>@return</p>
     */
    @NLog
    @RequestMapping(value = "/team_chargeback_rejected_list")
    public String teamChargebackRejectedList(Model model) {
        List list = zzCommonMangerExtService.queryTreeBookListByCode(ScProductConstant.RETURENED_REASON, 1, null);
        model.addAttribute("list", list); //退单原因
        return "zzsc/team/team_chargeback_rejected_list";
    }

    /**
     * <p>@Description 团队退单驳回数据</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/28 0028 11:39 创建时间</p>
     * <p>@return</p>
     */
    @NLog
    @RequestMapping(value = "/team_chargeback_rejected_list_data")
    @ResponseBody
    public DataTableResponse teamChargebackRejectedListData(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("start", r.getStart());
        params.put("limit", r.getLength());
        params.put("status", ScProductConstant.SC_ORDER_CHARGEBACK_TDBH);//退单驳回
        if (!net.dgg.iboss.base.util.StringUtils.isEmptyObj(params.get("customerPhone"))) {
            params.put("customerPhone", desUtil.encrypt(params.get("customerPhone").toString()));
        }
        Map fileMap = new HashMap();
        fileMap.put("signTime", "signTime");
        fileMap.put("lastRemarkTime", "lastRemarkTime");
        OrderHandleUtils.getOrderCol(r, params, fileMap);
        List<Map> listPage = zzAuditOrderServic.teamAuditOrderListData(params);
        String[] transColum = {"abandonReason"};
        listPage = translateUtil.translateList(transColum, listPage);
        String[] hideColum = {"customerPhone"};
        listPage = desUtil.decryptListMap(hideColum, listPage);
        CustomerNumberEncryptionUtil.encryptionList(hideColum, listPage);
        Integer count = Integer.parseInt(params.get("count").toString());
        return new DataTableResponse(r.getDraw(), count, count, listPage, "");
    }
}
